package com.ruoyi.sale.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.service.ICompanyInvoiceService;
import com.ruoyi.company.service.ICompanyOtherServer;
import com.ruoyi.company.service.ICompanyServer;
import com.ruoyi.company.utils.Util;
import com.ruoyi.expressdelivery.domain.ExpressDelivery;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.information.domain.Information;
import com.ruoyi.information.service.InformationService;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.mapper.ProcurementOrderMapper;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.product.service.ProductServer;
import com.ruoyi.productProof.service.ProductProofService;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.*;
import com.ruoyi.sale.domain.saleGoodsExcelDto.SaleGoodsExcelDto;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.mapper.SaleorderMapper;
import com.ruoyi.sale.service.IOutboundService;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author WangChangShuo
 * @date 2022年05月26日 9:42
 */
@RestController
@RequestMapping("/business/salegoods")
public class SaleGoodsController extends BaseController {

    @Autowired
    ISysDeptService iSysDeptService;

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    ISaleGoodsService iSaleGoodsService;

    @Autowired
    PurchaseOrderService purchaseOrderService;

    @Autowired
    ICompanyInvoiceService iCompanyInvoiceService;

    @Autowired
    ISaleorderService iSaleorderService;

    @Autowired
    AuditService auditService;

    @Autowired
    ICompanyServer iCompanyServer;

    @Autowired
    ICompanyOtherServer iCompanyOtherServer;

    @Autowired
    IOutboundService iOutboundService;

    @Autowired
    InformationService informationService;

    @Autowired
    ProductProofService proofService;

    @Autowired
    ExpressDeliveryService expressDeliveryService;

    @Autowired
    SaleGoodsMapper saleGoodsMapper;

    @Autowired
    SaleorderMapper saleorderMapper;

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    WarehousingMapper warehousingMapper;

    @Autowired
    private ProcurementServer procurementServer;

    @Autowired
    private ProcurementOrderMapper procurementOrderMapper;

    @Autowired
    private ProductServer productServer;

    @Autowired
    private ProductMapper productMapper;

    //定义新的方法用于删除文件目录中的文件
    public static boolean deleteFileAll(File file) {
        //首先判断是不是一个目录
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return false;
        } else {
            //获得目录下的所有文件
            File[] files = file.listFiles();
            for (File file1 : files) {
                if (file1.isDirectory()) {
                    //如果是目录，则递归，如果是文件，就删除
                    deleteFileAll(file1);
                } else {
                    file1.delete();
                }
            }
            return true;
        }
    }

    /**
     * 销货单管理界面
     *
     * @return
     */
    @RequiresPermissions("business:salegoods:view")
    @GetMapping()
    public String getlist(Model model) {
//        model.addAttribute("custObj", iSaleGoodsService.selectSaleGoodsCustObj(ShiroUtils.getSysUser().getCompanyId()));
        return "salegoods/list";
    }

    /**
     * 销售订单管理界面
     */
    @RequiresPermissions("business:salegoods:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo showlist(@RequestParam(value = "beginTime", required = false) String beginTime,
                                  @RequestParam(value = "endTime", required = false) String endTime,
                                  @RequestParam(value = "deptName", required = false) String deptName,
                                  @RequestParam(value = "saleGoodsStatus", required = false) String saleGoodsStatus,
                                  @RequestParam(value = "productType", required = false) String productType,
                                  @RequestParam(value = "batch", required = false) String batch) {

        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
        saleGoodsOrder.setBeginTime(beginTime);
        saleGoodsOrder.setEndTime(endTime);
        saleGoodsOrder.setDeptName(deptName);
        saleGoodsOrder.setProductType(productType);
        saleGoodsOrder.setBatch(batch);
        saleGoodsOrder.setSaleGoodsStatus(saleGoodsStatus);
        startPage();
        saleGoodsOrder.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        List<SaleGoodsOrder> list = iSaleGoodsService.selectSaleGoodsShowList(saleGoodsOrder);
//        if (!ShiroUtils.getSysUser().getDeptId().equals(ShiroUtils.getSysUser().getCompanyId())) {
//            saleGoodsOrder.setUserId(ShiroUtils.getSysUser().getUserId());
//        }
    /*    List<SaleGoodsModel> saleGoodsModels = saleGoodsMapper.selectAllModels();
        for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
            saleGoodsModel.setDeptId(208L);
            //ProductModel productModel = productMapper.selectModelByType(saleGoodsModel);
            Product product=productMapper.selectProductBysaleGoodsModel(saleGoodsModel);
            saleGoodsModel.setProductName(product.getProductName());

            //
         //   System.out.println("======="+saleGoodsModel.getSaleGoodsModelId());

            saleGoodsMapper.updateSaleGoodsModelById(saleGoodsModel);
        }*/
        //    List<Warehousing> warehousingList = warehousingMapper.selectWarehousingByDept(SecurityUtils.getDeptId());

 /*       for (Warehousing warehousing : warehousingList) {
            SaleGoodsModel saleGoodsModel=new SaleGoodsModel();
            saleGoodsModel.setDeptId(208L);
            saleGoodsModel.setProductType(warehousing.getProductType());
            ProductModel productModel=productMapper.selectModelByType(saleGoodsModel);
          //  System.out.println("销售副表的id====" + warehousing.getWarehousingId() + "产品型号=======" + productModel.getProductId());
            warehousing.setProductId(productModel.getProductId());
            warehousingMapper.updateProdcutId(warehousing);
        }*/
        return getDataTable(list);
    }

    /**
     * 确认付款
     */
    @Transactional
    @Log(title = "销货单确认付款", businessType = BusinessType.UPDATE)
    @PostMapping("/verifyInvoice/{saleGoodsId}")
    @ResponseBody
    public int verifyInvoice(@PathVariable("saleGoodsId") Long saleGoodsId) {
        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
        saleGoodsOrder.setSaleGoodsId(saleGoodsId);
        saleGoodsOrder.setIsInvoice("1");
        int a = iSaleGoodsService.updateSaleorderOrderIsPay(saleGoodsOrder);
        if (a > 0) {
            return 1;
        } else {
            return 0;
        }

    }


/*   @GetMapping("/selectSaleorderAI/{deptId}")
    @ResponseBody
    public ResponseEntity<List<SaleorderDto>> selectSaleorderAI(@PathVariable("deptId") Long deptId) {
        List<SaleorderOrder> list = saleorderMapper.selectSaleorderAI(deptId);
        List<SaleorderDto> list1 = new ArrayList<>();
        for (SaleorderOrder saleorderOrder : list) {
            SaleorderDto saleorderDto = new SaleorderDto(saleorderOrder);
            list1.add(saleorderDto);
        }
        return ResponseEntity.ok(list1);
    }
    */

    @GetMapping("/selectSaleorderAI")
    @ResponseBody
    public List<SaleorderOrder> selectSaleorderAI(@RequestParam(value = "deptId", required = false) Long deptId,
                                                  @RequestParam(value = "beginTime", required = false) String beginTime) {
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setDeptId(deptId);
        saleorderOrder.setBeginTime(beginTime);
        List<SaleorderOrder> list = saleorderMapper.selectSaleorderAI(saleorderOrder);
        return list;
    }

    @GetMapping("/selectWarehousingAI/{deptId}")
    @ResponseBody
    public List<Warehousing> selectWarehousingAI(@PathVariable("deptId") Long deptId) {
        List<Warehousing> list = warehousingMapper.selectWarehousingAI(deptId);
        return list;
    }

    @GetMapping("/selectprocurementOrderAI")
    @ResponseBody
    public List<ProcurementOrder> selectprocurementOrderAI(@RequestParam(value = "deptId", required = false) Long deptId,
                                                           @RequestParam(value = "beginTime", required = false) String beginTime) {

        ProcurementOrder procurementOrder = new ProcurementOrder();
        procurementOrder.setDeptId(deptId);
        procurementOrder.setBeginTime(beginTime);
        List<ProcurementOrder> list = procurementOrderMapper.selectProcurementOrderAI(procurementOrder);
        return list;

    }

    @GetMapping("/selectSfInformationa")
    @ResponseBody
    public List<ExpressDelivery> selectSfInformationa(HttpServletRequest request) {
        String saleordernum = request.getParameter("saleordernum");
        List<ExpressDelivery> list = new ArrayList<>();
        try {
            list = expressDeliveryService.selectSfInformation(saleordernum);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @GetMapping("/selectOrder")
    @ResponseBody
    public Map<String, Object> selectOrder(HttpServletRequest request) {
        Map<String, Object> resMap = new HashMap<>();
        String msgData = request.getParameter("msgData");
        try {
            resMap = expressDeliveryService.selectOrder(msgData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap;
    }

    @PostMapping("/selectremakrs")
    @ResponseBody
    public Map<String, Object> selectRemark(HttpServletRequest request) throws Exception {
        Map<String, Object> resMap = new LinkedHashMap<>();
        String saleordernum = request.getParameter("saleordernum");
        try {
            List<ExpressDelivery> list = expressDeliveryService.selectInformation(saleordernum);
            if (list.size() != 0) {
                resMap.put("code", "0");
                resMap.put("result", list);
            } else {
                resMap.put("code", "-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap;
    }

    @GetMapping("/selectshinformation")
    @ResponseBody
    public Map<String, Object> selectshinformation(HttpServletRequest request) throws Exception {
        Map<String, Object> resMap = new LinkedHashMap<>();
        String saleordernum = request.getParameter("saleordernum");
        try {
            String a = saleGoodsMapper.selectsalenuma(saleordernum);
            if (a == null || a.isEmpty()) {
                resMap.put("code", 200);
            } else {
                Company company = companyMapper.selectCompany(SecurityUtils.getLoginUser().getCompanyId());
                ExpressDelivery list = expressDeliveryService.selectExpressDelivery(a);
                list.setFhdz(company.getRasProvince() + company.getRasCity() + company.getRasDistrict() + company.getRasAddress());
                if (list != null) {
                    resMap.put("code", 200);
                    resMap.put("result", list);
                } else {
                    resMap.put("code", 200);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap;
    }

    @PostMapping("/selectSfInformation")
    @ResponseBody
    public Map<String, Object> selectSfInformation(HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        Map<String, Object> resMap = new LinkedHashMap<>();
        String saleordernum = request.getParameter("saleordernum");
        String a = saleGoodsMapper.selectsalenuma(saleordernum);
        List<SaleGoodsOrder> list2 = saleGoodsMapper.selectsalenum(saleordernum);
        List<ExpressDelivery> list1;
        try {

            List list = expressDeliveryService.selectSfInformation(saleordernum);
            list1 = expressDeliveryService.selectInformation(a);
            if (list.size() != 0) {
                resMap.put("result", list);
                resMap.put("list1", list1);
                resMap.put("list2", list2);
                resMap.put("code", "0");
            } else {
                resMap.put("code", "-1");
            }
        } catch (Exception e) {
            resMap.put("code", "-1");
            e.printStackTrace();
        }
        return resMap;
    }

    /**
     * 新增销货单 剩余数量
     */
    @GetMapping("/selectInformation")
    public Map<String, Object> add() {
        Map<String, Object> resMap = new HashMap<>();
        //使用SimpleDateFormat的parse()方法生成Date
        SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dates = a.parse(a.format(new Date()));
            resMap.put("saleGoodsNum", orderNum(dates, 2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", companyId);
        List<SysUser> sysUsers = iSysUserService.selectCustAndSuppById(companyId);
        List<SysUser> user = iSysUserService.selectSalesmanList(companyId);
        Company companyInvoice = companyMapper.selectByCompanyId(companyId);
        if (sysUsers != null) {
            resMap.put("sysUsers", sysUsers);
        }
        if (user != null) {
            resMap.put("user", user);
        }
        if (companyInvoice != null) {
            resMap.put("taxRate", companyInvoice.getTaxRate());
        }
        return resMap;
    }

    public String orderNum(Date date, int i) {
        return purchaseOrderService.orderNum(date, i);
    }

    /**
     * 选择销售订单页面
     */
    @GetMapping("/selectSaleorder")
    public Map<String, Object> selectSaleorderget() {
        Map<String, Object> resMap = new HashMap<>();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();

        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setDeptId(companyId);
       /*if (!ShiroUtils.getSysUser().getDeptId().equals(ShiroUtils.getSysUser().getCompanyId())) {
            saleorderOrder.setUserId(SecurityUtils.getUserId());
        }*/
        List<SaleorderOrder> list = iSaleorderService.selectSaleorderCustObj(saleorderOrder);
        resMap.put("custObj", list);

//        Map<String, Object> map = new HashMap<>();
//        saleorderOrder.setDeptId(companyId);
//        saleorderOrder.setIsCreateGoods("1");
//
//        List<SaleorderOrder> saleorderOrderList = new ArrayList<SaleorderOrder>();
//        List<SaleorderModel> saleorderModelList = new ArrayList<SaleorderModel>();
//
//        saleorderOrder.setDeptId(companyId);
//        saleorderOrderList = iSaleorderService.selectOrder(saleorderOrder);
//
//        for (int i = 0; i < saleorderOrderList.size(); i++) {
//            SaleorderOrder saleorderOrder1 = saleorderOrderList.get(i);
//            saleorderModelList.addAll(saleorderOrder1.getSaleorderModels());
//        }
//        model.addAttribute("saleorderOrderList", saleorderOrderList);
//       model.addAttribute("saleorderModelList", saleorderModelList);
        return resMap;
    }

    @GetMapping("/selectSaleorderes/{columnId}")
    public Map<String, Object> selectSaleorderes(@PathVariable("columnId") Long columnId) {

        Map<String, Object> resMap = new HashMap<>();
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        Long companyId = ShiroUtils.getSysUser().getCompanyId();
        saleorderOrder.setDeptId(companyId);
        saleorderOrder.setIsCreateGoods("1");

        List<SaleorderOrder> saleorderOrderList = new ArrayList<SaleorderOrder>();
        List<SaleorderModel> saleorderModelList = new ArrayList<SaleorderModel>();
        if (saleorderOrder.getCompanyId() == null) {
            resMap.put("saleorderOrderList", saleorderOrderList);
            resMap.put("saleorderModelList", saleorderModelList);
        }

        saleorderOrder.setDeptId(companyId);
        saleorderOrder.setCompanyId(columnId);
        saleorderOrderList = iSaleorderService.selectOrder(saleorderOrder);

        for (int i = 0; i < saleorderOrderList.size(); i++) {
            SaleorderOrder saleorderOrder1 = saleorderOrderList.get(i);
            saleorderModelList.addAll(saleorderOrder1.getSaleorderModels());
        }
        for (SaleorderModel saleorderModel : saleorderModelList) {
            if (saleorderModel.getUnit().equals("盒") || saleorderModel.getUnit() == "盒") {
                List<Integer> list1 = procurementServer.selectProductType(saleorderModel.getProductType());
                int a = list1.get(0);
                if (a != 0) {
                    int b = saleorderModel.getRemainingNum() / a;
                    int c = saleorderModel.getExecuteNum() / a;
                    saleorderModel.setRemainingNum(b);
                    saleorderModel.setExecuteNum(c);
                }
            }
        }

        resMap.put("saleorderOrderList", saleorderOrderList);
        resMap.put("saleorderModelList", saleorderModelList);
        return resMap;
    }

    /**
     * 选择销售订单列表 主表
     */
    @PostMapping("/selectSaleorderOrderList")
    @ResponseBody
    public TableDataInfo list(SaleorderOrder saleorderOrder) {
        startPage();
        Long companyId = ShiroUtils.getSysUser().getCompanyId();
        saleorderOrder.setDeptId(companyId);
        saleorderOrder.setIsCreateGoods("1");
        List<SaleorderOrder> list = new ArrayList<SaleorderOrder>();
        if (saleorderOrder.getDeptName() != null && "".equals(saleorderOrder.getDeptName())) {
            return getDataTable(list);
        }
        list = iSaleorderService.selectSaleorderOrderListByStatusIsOne(saleorderOrder);
        return getDataTable(list);
    }

    @GetMapping("/selectSaleorders")
    @ResponseBody
    public Map<String, Object> selectSaleorders(@RequestParam(value = "companyId", required = false) Long companyId,
                                                @RequestParam(value = "beginTime", required = false) String beginTime,
                                                @RequestParam(value = "endTime", required = false) String endTime) {

        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setCompanyId(companyId);
        saleorderOrder.setBeginTime(beginTime);
        saleorderOrder.setEndTime(endTime);
        startPage();
        Map<String, Object> map = new HashMap<>();
        Long deptId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        saleorderOrder.setDeptId(companyId);
        saleorderOrder.setIsCreateGoods("1");
        List<SaleorderOrder> saleorderOrderList = new ArrayList<>();
        List<SaleorderModel> saleorderModelList = new ArrayList<>();
        if (saleorderOrder.getCompanyId() == null) {
            map.put("saleorderOrderList", saleorderOrderList);
            map.put("saleorderModelList", saleorderModelList);
            return map;
        }

        saleorderOrder.setDeptId(deptId);
        saleorderOrderList = iSaleorderService.selectOrder(saleorderOrder);
        for (int i = 0; i < saleorderOrderList.size(); i++) {
            SaleorderOrder saleorderOrder1 = saleorderOrderList.get(i);
            saleorderModelList.addAll(saleorderOrder1.getSaleorderModels());
        }

        for (SaleorderModel saleorderModel : saleorderModelList) {
            if (saleorderModel.getAllNum() != 0) {
                if (saleorderModel.getUnit().equals("盒") || saleorderModel.getUnit() == "盒") {
                    int b = saleorderModel.getRemainingNum() / saleorderModel.getFactor().intValue();
                    int c = saleorderModel.getExecuteNum() / saleorderModel.getFactor().intValue();
                    int d = saleorderModel.getAllNum() / saleorderModel.getFactor().intValue();
                    saleorderModel.setRemainingNum(b);
                    saleorderModel.setExecuteNum(c);
                }
            }
        }

        map.put("saleorderOrderList", saleorderOrderList);
        map.put("saleorderModelList", saleorderModelList);
        return map;
    }

    /**
     * 选择销售订单 子表的数据
     */
    @PostMapping("/selectSaleorderModelList")
    @ResponseBody
    public TableDataInfo selectSaleorderModelList(Long saleorderId) {
        startPage();
        HashMap hashMap = new HashMap();
        hashMap.put("saleorderId", saleorderId);
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
        if (saleorderOrder != null) {
            List<SaleorderModel> saleorderModels = saleorderOrder.getSaleorderModels();
            return getDataTable(saleorderModels);
        } else {
            List<SaleorderModel> list = new ArrayList();
            return getDataTable(list);
        }
    }

    /**
     * 选择销售订单 子表的数据
     */
    @PostMapping("/selectSaleorderById")
    @ResponseBody
    public SaleorderOrder selectSaleorderById(Long saleorderId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
        return saleorderOrder;
    }

    /**
     * 选择产品
     */
    @GetMapping("/selectProduct/{saleorderId}")
    public String selectProductget(@PathVariable("saleorderId") String saleorderId, Model model) {
        model.addAttribute("saleorderId", saleorderId);
        return "salegoods/selectProduct";
    }

    /**
     * 选择产品 主表的数据
     */
    @PostMapping("/selectSaleModelList/{saleorderId}")
    @ResponseBody
    public TableDataInfo selectSaleModelList(@PathVariable("saleorderId") Long saleorderId, @PathVariable("productName") String productName, @PathVariable("productType") String productType) {

        startPage();
        HashMap hashMap = new HashMap();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        if (!"".equals(productName) && productName != null) {
            hashMap.put("productName", productName);
        }
        if (!"".equals(productType) && productType != null) {
            hashMap.put("productType", productType);
        }
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
        if (saleorderOrder != null) {
            List<SaleorderModel> saleorderModels = saleorderOrder.getSaleorderModels();
            return getDataTable(saleorderModels);
        } else {
            List<SaleorderModel> list = new ArrayList();
            return getDataTable(list);
        }
    }

    /**
     * 选择产品批次 带出数据
     */
    @PostMapping("/selectSaleorderModel")
    @ResponseBody
    public List<SaleGoodsModel> selectSaleorderModel(String data, Long saleorderId) {
        JSONArray jsonArray = JSONArray.parseArray(data);
        List<SaleGoodsModel> saleGoodsModels = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            //唯一码
            Object modelCode = jsonObject.get("modelCode");
            //批次
            Object batch = jsonObject.get("batch");
            //出库数量
            Object num = jsonObject.get("num");
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("modelCode", modelCode);
            hashMap.put("batch", batch);
            hashMap.put("saleorderId", saleorderId);
            hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
            hashMap.put("num", num);
            SaleGoodsModel saleGoodsModel = iSaleGoodsService.selectSaleGoodsModel(hashMap);
            saleGoodsModels.add(saleGoodsModel);
        }
        return saleGoodsModels;
    }

    @PostMapping("/addAfter")
    @ResponseBody
    public AjaxResult addAfter(@RequestBody SaleGoodsOrder saleGoodsOrder) {

        SaleGoodAfter saleGoodAfter = new SaleGoodAfter();
        saleGoodAfter.setSaleGoodsId(saleGoodsOrder.getSaleGoodsId());
        saleGoodAfter.setDeptId(saleGoodsOrder.getDeptId());
        saleGoodAfter.setCustomerId(saleGoodsOrder.getCustomerId());
        saleGoodAfter.setSaleGoodsNum(saleGoodsOrder.getSaleGoodsNum());
        int insertOrderNum = iSaleGoodsService.addAfter(saleGoodAfter);
        if (insertOrderNum >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }
    }

    /**
     * 新增保存销货单
     */
    @RequiresPermissions("business:salegoods:add")
    @Transactional
    @Log(title = "新增保存销货单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@RequestBody SaleGoodsOrder saleGoodsOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String orderid = getStrNew(); // getStr();
        //验证 前端 子表 是否有产品
        if (saleGoodsOrder.getSaleGoodsModels() == null) {
            return AjaxResult.error("请选择要出库的产品");
        }

        String saleGoodsNum = saleGoodsOrder.getSaleGoodsNum();
        Long companyId = sysUser.getCompanyId();
        HashMap<String, Object> map = new HashMap<>();
        map.put("saleGoodsNum", saleGoodsNum);
        map.put("deptId", companyId);
        SaleGoodsOrder saleGoodsOrder1 = iSaleGoodsService.selectSaleGoodsByIds(map);
        if (saleGoodsOrder1 != null) {
            //使用SimpleDateFormat的parse()方法生成Date
            SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
            Date dates = null;
            try {
//              dates = a.parse(a.format(new Date()));
                dates = a.parse(a.format(saleGoodsOrder.getSaleGoodsDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String s = orderNum(dates, 2);
            saleGoodsOrder.setSaleGoodsNum(s);
        }

        //验证 同 批次 同产品id 同产品型号 数量加起来是否大于该现存数量
//        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size(); i++) {
//            SaleGoodsModel saleGoodsModel = saleGoodsOrder.getSaleGoodsModels().get(i);
//            for (int j = 0; j < saleGoodsOrder.getSaleGoodsModels().size() - 1; j++) {
//                SaleGoodsModel saleGoodsModel = saleGoodsOrder.getSaleGoodsModels().get(i);
//            }
//        }

        saleGoodsOrder.setSaleGoodsStatus("1");
        saleGoodsOrder.setCreateBy(sysUser.getNickName());
        saleGoodsOrder.setDeptId(sysUser.getCompanyId());
        //状态 0 申请中
        saleGoodsOrder.setSaleGoodsStatus("0");

        saleGoodsOrder.setOrderId(orderid);

        int insertOrderNum = iSaleGoodsService.insertSaleGoodsOrder(saleGoodsOrder);
        List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder.getSaleGoodsModels();

        List<SaleNumRecord> saleNumRecords = new ArrayList<SaleNumRecord>();

        if (saleGoodsModels != null) {
            for (int i = 0; i < saleGoodsModels.size(); i++) {
                saleGoodsModels.get(i).setSaleGoodsId(saleGoodsOrder.getSaleGoodsId());
                SaleGoodsModel saleGoodsModel = saleGoodsModels.get(i);
                saleGoodsModel.setDeptId(companyId);
                iSaleGoodsService.insertSaleGoodsModels(saleGoodsModel);
                SaleNumRecord saleNumRecord = new SaleNumRecord();
                saleNumRecord.setSaleGoodsId(saleGoodsModel.getSaleGoodsId());
                saleNumRecord.setExecuteNum(saleGoodsModel.getNum());
                saleNumRecord.setRemainingNum(saleGoodsModel.getRemainingNum());
                saleNumRecord.setSaleGoodsModelId(saleGoodsModel.getSaleGoodsModelId());
                saleNumRecord.setSaleorderModelId(saleGoodsModel.getSaleorderModelId());
                saleNumRecord.setCreateBy(sysUser.getNickName());
                saleNumRecords.add(saleNumRecord);
            }
        }

        iSaleGoodsService.insertSaleNumRecordList(saleNumRecords);
        //更新 选择的销售订单子表 中的三个字段  execute_status  execute_num remaining_num
     /*   for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
            SaleorderModel saleorderModel = saleorderOrder.getSaleorderModels().get(i);

            if (saleorderModel.getRemainingNum() == 0) {
                //1 已执行
                saleorderModel.setExecuteStatus("1");
            } else {
                //2 部分执行
                saleorderModel.setExecuteStatus("2");
            }
            //iSaleorderService.updateSaleorderModel(saleorderModel);
        }*/
        //添加审核订单
        Audit audit = new Audit();
        //销货单Id
        audit.setOrderId(saleGoodsOrder.getSaleGoodsId());
        //登陆人的companyid
        audit.setCompanyId(sysUser.getCompanyId());
        //主表的含税金额
        audit.setTaxAmount(saleGoodsOrder.getSaleGoodsTaxamount());
        //业务员id
        audit.setUserId(saleGoodsOrder.getUserId());
        //客户id
        audit.setSupplierId(saleGoodsOrder.getCompanyId());
        //订单编号
        audit.setOrderNum(saleGoodsOrder.getSaleGoodsNum());
        //3为销货单
        audit.setOrderType("3");
        //状态0为 未审核
        audit.setAuditStatus("0");
        int insertAudit = auditService.insertAudit(audit);
        if (insertOrderNum >= 1 && insertAudit >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }
    }

    /**
     * 修改销货单
     */
    @GetMapping("/edit/{saleGoodsId}")
    public Map<String, Object> edit(@PathVariable("saleGoodsId") Long saleGoodsId) {
        Map<String, Object> resMap = new HashMap<>();
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleGoodsId", saleGoodsId);
        hashMap.put("deptId", deptId);
        SaleGoodsOrder saleGoodsOrder = iSaleGoodsService.selectSaleGoodsById(hashMap);
        //判断子集是否存在
        if (saleGoodsOrder.getSaleGoodsModels().get(0).getSaleGoodsModelId() == null) {
            //没有的话 给个空的集合
            List<SaleGoodsModel> list = new ArrayList();
            saleGoodsOrder.setSaleGoodsModels(list);
            resMap.put("saleGoodsOrder", saleGoodsOrder);
        } else {
            List<SaleGoodsModel> list1 = saleGoodsOrder.getSaleGoodsModels();
            for (SaleGoodsModel saleGoodsModel : list1) {
                Long factor = saleGoodsModel.getFactor() == null ? 1 : saleGoodsModel.getFactor();
                if (saleGoodsModel.getUnit().equals("盒")) {
                    Long b = saleGoodsModel.getRemainingNum() / factor;
                    saleGoodsModel.setRemainingNum(b.intValue());
                    saleGoodsModel.setAmount(saleGoodsModel.getAmount() / factor.intValue());
                    saleGoodsModel.setExecuteNum(saleGoodsModel.getExecuteNum() / factor.intValue());
                }
            }
            resMap.put("saleGoodsOrder", saleGoodsOrder);
        }
        List<SysUser> sysUsers = iSysUserService.selectSupplierById(sysUser.getCompanyId());
        List<SysUser> user = iSysUserService.selectSalesmanList(sysUser.getCompanyId());
        Product product = new Product();
        product.setDeptId(sysUser.getCompanyId());
        Map<String, Object> map1 = new HashMap<>();
        map1.put("deptId", sysUser.getCompanyId());
        if (sysUsers != null) {
            resMap.put("sysUsers", sysUsers);
        }
        if (user != null) {
            resMap.put("user", user);
        }

        resMap.put("taxRate", saleGoodsOrder.getTaxRate());

        // 获取上一条临近的ID
        resMap.put("previousId", iSaleGoodsService.querypreviousId(saleGoodsId));
        // 获取下一条临近的ID
        resMap.put("nextId", iSaleGoodsService.queryNextId(saleGoodsId));
        return resMap;
    }

    /**
     * 修改保存销货单
     */
    @RequiresPermissions("business:salegoods:edit")
    @Log(title = "修改保存销货单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody SaleGoodsOrder saleGoodsOrder, @RequestBody SaleorderOrder saleorderOrder) {
        if (saleGoodsOrder.getSaleGoodsModels() == null) {
            return AjaxResult.error("产品不能为空");
        }
        return toAjax(iSaleGoodsService.editSave(saleGoodsOrder, saleorderOrder));
    }

    /**
     * 根据销货单生成 随货单ajax 随货单是把该销货单 所有的都打印
     */
    @Transactional
    @PostMapping("/dataIntowithOrder")
    @ResponseBody
    public JSONObject dataIntoContract(Long saleGoodsId, int rowFalg) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleGoodsId", saleGoodsId);
        SaleGoodsOrder saleGoodsOrder = iSaleGoodsService.selectSaleGoodsById(hashMap);

        HashMap hashMap1 = new HashMap();
        hashMap1.put("deptId", SecurityUtils.getLoginUser().getCompanyId());
        hashMap1.put("companyId", saleGoodsOrder.getCustomerId());
        hashMap1.put("gradeStatus", "02");
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(hashMap1);

        JSONObject jsonObject = new JSONObject();
        //本公司名称
        jsonObject.put("deptNameVal", iSysDeptService.selectDeptById(SecurityUtils.getLoginUser().getCompanyId()).getDeptName());
        //单据编号 是销货单的编号
        jsonObject.put("contractNo", saleGoodsOrder.getSaleGoodsNum());
        //客户名称
        jsonObject.put("purchaseName", saleGoodsOrder.getDeptName());
        //单据日期 contractDate
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        jsonObject.put("contractDate", fmt.format(saleGoodsOrder.getSaleGoodsDate()));
        Long customerId = saleGoodsOrder.getCustomerId();

        //客户地址
        Company company = iCompanyServer.selectByCompanyId(customerId);
        jsonObject.put("contractAddress", company.getProvince() + company.getCity() + company.getOtherCorporateAddress());

        //收货地址 warehouseAddress
        Company mycompany = iCompanyServer.selectByCompanyId(ShiroUtils.getSysUser().getCompanyId());
        jsonObject.put("warehouseAddress", mycompany.getProvince() + mycompany.getCity() + mycompany.getOtherCorporateAddress());

        //公司电话
        jsonObject.put("custPhone", iCompanyInvoiceService.selectByCompanyId(customerId).getCorporateRegisterPhone());
        //销售订单产品
        JSONArray jsonArrayModel = new JSONArray();
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            jsonArrayModel.add(saleGoodsOrder.getSaleGoodsModels().get(i));
        }

        jsonObject.put("models", jsonArrayModel);
        //总数量
        int totalNum = 0;
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            totalNum += saleGoodsOrder.getSaleGoodsModels().get(i).getNum();
        }
        jsonObject.put("totalNum", totalNum);
        //总金额tfr
        BigDecimal totalMoney = new BigDecimal("0.00");
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            totalMoney = totalMoney.add(saleGoodsOrder.getSaleGoodsModels().get(i).getTaxTotal());
        }

        jsonObject.put("totalMoney", totalMoney);
        //制单人
        jsonObject.put("makeOrderName", iSysUserService.selectUserByLoginName(saleGoodsOrder.getCreateBy()).getUserName());

        //收货人 companyOther
        //收货人及联系电话
        String str = companyOther.getConsigneeAndPhone();

        String reg = "[^\u4e00-\u9fa5]";
        if (!"".equals(str) && str != null) {
            str = str.replaceAll(reg, "");
        } else {
            str = "";
        }

        jsonObject.put("consignee", str);
        //出库单说明信息

        JSONArray jsonContractTerms = new JSONArray();
        Company company1 = iCompanyServer.selectByCompanyId(SecurityUtils.getLoginUser().getCompanyId());
        String contractTerms = company1.getOutboundDeliveryMemo();
        if (contractTerms == null || "".equals(contractTerms)) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "您的出库单说明信息为空,请先在个人信息-我的公司档案完善出库单说明信息。");
            throw new RuntimeException("您的出库单说明信息为空,请先在个人信息-我的公司档案完善出库单说明信息。");
        }
        if (contractTerms != null) {
            //根据回车进行分割
            String[] contractTermsArr = contractTerms.split("\\r?\\n");
            for (int i = 0; i < contractTermsArr.length; i++) {
                //每行108个字符
                String[] strings = Util.stringToArray(contractTermsArr[i]);
                String interception = Util.interception(strings, 108);
                //根据回车进行分割
                String[] split = interception.split("换行测试");
                for (int j = 0; j < split.length; j++) {
                    String s = split[j];
                    //第一行的时候拼接上 “说明：”
                    jsonContractTerms.add(s);
                }
            }
            jsonObject.put("contractTerms", jsonContractTerms);
        } else {
            jsonObject.put("contractTerms", "");
        }
        return jsonObject;
    }

    /**
     * 随货单 剩余的数据
     */
    @PostMapping("/dataIntowithOrderOtherData")
    @ResponseBody
    public JSONObject dataIntowithOrderOtherData(String[] tableData, Long saleGoodsId) {
        //每一页封装为一哥JSONObject
        JSONObject jsonObject = new JSONObject();
        //处理数据 传过来的以，分割的字符串
        //每条数据查询出从表主键id 放到集合中
        ArrayList<Long> tableDataId = new ArrayList();
        for (int i = 0; i < tableData.length; i++) {
            String[] split = tableData[i].split(",");
            SaleGoodsModel saleGoodsModel = new SaleGoodsModel();
            //salegoodsid
            saleGoodsModel.setSaleGoodsId(saleGoodsId);
            //productId
            saleGoodsModel.setProductId(Long.valueOf(split[0]));
            //productType
            saleGoodsModel.setProductType(split[1]);
            //batch
            saleGoodsModel.setBatch(split[8]);
            SaleGoodsModel model = iSaleGoodsService.selectSaleGoodsModelByIds(saleGoodsModel);
            tableDataId.add(model.getSaleGoodsModelId());
        }

        //根据销货单id查询 销货单从表
        List<SaleGoodsModel> saleGoodsModels = iSaleGoodsService.selectSaleGoodsModelById(saleGoodsId);

        //新建对比数组，用于判断执行什么操作
        ArrayList<Long> arrayList = new ArrayList();
        for (SaleGoodsModel model : saleGoodsModels) {
            arrayList.add(model.getSaleGoodsModelId());
        }

        //数组中剩余的数就是需要删除的数据
        for (Long o1 : tableDataId) {
            Iterator<Long> iterator = arrayList.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().equals(o1)) {
                    iterator.remove();
                }
            }
        }

        //剩下的则是 要重新生成的 随货单
        //分为几页arrayList.size()/tableData.length+1

        jsonObject.put("page", (int) Math.ceil((double) arrayList.size() / tableData.length));

        //如果剩余的只有一页了
        if (arrayList.size() <= tableData.length) {
            //总数量
            int totalNuma = 0;
            //总金额
            BigDecimal totalMoneya = new BigDecimal("0.00");
            JSONArray jsonArrayModel = new JSONArray();
            for (int j = 0; j < arrayList.size(); j++) {
                //销售订单产品
                SaleGoodsModel saleGoodsModel = iSaleGoodsService.selectSaleGoodsModelByModelId(arrayList.get(j));
                jsonArrayModel.add(saleGoodsModel);
                totalNuma += saleGoodsModel.getNum();
                totalMoneya = totalMoneya.add(saleGoodsModel.getTaxTotal());
            }
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("models", jsonArrayModel);
            jsonObject1.put("totalNum", totalNuma);
            jsonObject1.put("totalMoney", totalMoneya);
            jsonObject.put("page0", jsonObject1);
        } else {
            //这里则是 剩余的超过一页
            //外层for循环控制 第几页
            for (int i = 0; i < (int) Math.ceil((double) arrayList.size() / tableData.length); i++) {
                //当页总数量
                int totalNum = 0;
                //当页总金额
                BigDecimal totalMoney = new BigDecimal("0.00");
                //取最后一页的条数 取模
                int lastRow = arrayList.size() % tableData.length;
                //不是最后一页的话
                //存放model数据
                JSONArray jsonArrayModel1 = new JSONArray();
                if (i != ((int) Math.ceil((double) arrayList.size() / tableData.length)) - 1) {
                    for (int j = i * tableData.length; j < tableData.length + i * tableData.length; j++) {
                        //销售订单产品
                        SaleGoodsModel saleGoodsModel = iSaleGoodsService.selectSaleGoodsModelByModelId(arrayList.get(j));
                        jsonArrayModel1.add(saleGoodsModel);
                        totalNum += saleGoodsModel.getNum();
                        totalMoney = totalMoney.add(saleGoodsModel.getTaxTotal());
                    }
                } else {
                    //是最后一页的话
                    for (int j = arrayList.size() - lastRow; j < arrayList.size(); j++) {
                        //销售订单产品
                        SaleGoodsModel saleGoodsModel = iSaleGoodsService.selectSaleGoodsModelByModelId(arrayList.get(j));
                        jsonArrayModel1.add(saleGoodsModel);
                        totalNum += saleGoodsModel.getNum();
                        totalMoney = totalMoney.add(saleGoodsModel.getTaxTotal());
                    }
                }
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("models", jsonArrayModel1);
                jsonObject1.put("totalNum", totalNum);
                jsonObject1.put("totalMoney", totalMoney);
                jsonObject.put("page" + i, jsonObject1);
            }

        }
        jsonObject.put("lastRow", tableData.length);
        return jsonObject;
    }

    /**
     * 查看出库单记录
     */
    @GetMapping("/selectOutbound/{saleGoodsId}")
    public String selectOutbound(@PathVariable("saleGoodsId") Long saleGoodsId, Model model) {
        //OutboundOrder outboundOrder = iOutboundService.selectOutboundBySaleGoodsId(saleGoodsId);
        model.addAttribute("saleGoodsId", saleGoodsId);
        return "salegoods/selectOutbound";
    }

    /**
     * 选择产品 主表的数据
     */
    @GetMapping("/selectOutboundList/{saleGoodsId}")
    @ResponseBody
    public TableDataInfo selectOutboundList(@PathVariable("saleGoodsId") Long saleGoodsId) {
        startPage();
        //List<OutboundOrder> outboundOrder = iOutboundService.selectOutboundBySaleGoodsId(saleGoodsId);
        List<OutboundOrder> outboundOrder = iOutboundService.selectOutboundList(saleGoodsId);
        return getDataTable(outboundOrder);
    }

    /**
     *
     */
    @GetMapping("/selectOutboundModelList")
    @ResponseBody
    public TableDataInfo selectOutboundModelList(@RequestParam(value = "outboundId", required = false) Long outboundId) {
        OutboundOrder outboundOrder = iOutboundService.selectOutboundById(outboundId);
        List<OutboundModel> outboundModels;
        if (outboundId != null) {
            outboundModels = outboundOrder.getOutboundModels();
        } else {
            outboundModels = new ArrayList<>();
        }

        return getDataTable(outboundModels);
    }

    /**
     * 查询销货单 剩余没有出库的订单信息
     */
    @GetMapping("/selectSaleGoodsResidue/{saleGoodsId}")
    @ResponseBody
    public AjaxResult selectSaleGoodsResidue(@PathVariable("saleGoodsId") Long saleGoodsId) {
        AjaxResult result = new AjaxResult();
        List<SaleGoodsOrder> saleGoodsOrders = iSaleGoodsService.selectSaleGoodsResidue(saleGoodsId);
        result.put("saleGoodsOrders", saleGoodsOrders);
        // 获取上一条临近的ID
        result.put("previousId", iSaleGoodsService.querypreviousId(saleGoodsId));
        // 获取下一条临近的ID
        result.put("nextId", iSaleGoodsService.queryNextId(saleGoodsId));

        return result;
    }

    /**
     * 查询打印随货单资料
     */
    @GetMapping("/printFile/{outboundId}")
    public String printFile(@PathVariable("outboundId") String outboundId, ModelMap mmap) {
        mmap.addAttribute("outboundId", outboundId);
        return "salegoods/printFiles";
    }

    /**
     * 查询并合并打印随货单资料
     */

    @GetMapping("/printFiles/{saleGoodsId}/{printFileKey}")
    @ResponseBody
    public AjaxResult printFiles(@PathVariable("saleGoodsId") Long saleGoodsId, @PathVariable("printFileKey") String printFileKey) {
        List<Map> maps = new ArrayList<>();
        //查询销货单打印记录
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("saleGoodsId", saleGoodsId);
        resMap.put("deptId", SecurityUtils.getLoginUser().getUser().getDeptId());
        SaleGoodsOrder saleGoodsOrder = iSaleGoodsService.selectSaleGoodsById(resMap);
        List<SaleGoodsModel> saleGoodsModelList = saleGoodsOrder.getSaleGoodsModels();
        for (SaleGoodsModel saleGoodsModel : saleGoodsModelList) {
            Map<String, Object> map = new HashMap<>();
            map.put("saleGoodsId", saleGoodsId);
            map.put("productId", saleGoodsModel.getProductId());
            map.put("modelCode", saleGoodsModel.getModelCode());
            map.put("productType", saleGoodsModel.getProductType());
            map.put("batch", saleGoodsModel.getBatch());
            map.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
            maps.add(map);
        }

        String[] split = printFileKey.split(",");
        Map<String, String> FileHashMap = new HashMap<>();
        for (String s : split) {
            if (s.equals("0")) {
                //查询销货单子表数据
                List<SaleGoodsModel> saleGoodsModels = iSaleGoodsService.selectSaleGoodsModelByListes(maps);
                List<Map> saleGoodsModelMaps = new ArrayList<>();
                Map<String, Object> saleGoodsModelMap = new HashMap<>();
                for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
                    saleGoodsModelMap.put("batch", saleGoodsModel.getBatch());
                    saleGoodsModelMap.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
                    saleGoodsModelMap.put("productId", saleGoodsModel.getProductId());
                    saleGoodsModelMap.put("productType", saleGoodsModel.getProductType());
                    saleGoodsModelMap.put("medicalNumber", saleGoodsModel.getMedicalNumber());
                    saleGoodsModelMaps.add(saleGoodsModelMap);
                }

                List<Product> products = productServer.selectProductProofListes(saleGoodsModelMaps);
                for (int i = 0; i < products.size(); i++) {
                    Product product = products.get(i);
                    if (product.getProductProofName() != null && product.getProductProofAddress() != null) {
                        if (!product.getProductProofName().equals("") && !product.getProductProofAddress().equals("")) {
                            FileHashMap.put(product.getProductProofName(), product.getProductProofAddress());
                            return new AjaxResult(0, "生成文件成功", product.getProductProofAddress());
                        }
                    }
                }

            } else {
                //查询产品入库记录数据
                List<Information> informationList = informationService.selectInformationByList(maps);
                if (s.equals("1")) {
                    for (Information information : informationList) {
                        if (information.getFactoryInspectionName() != null && information.getFactoryInspectionAddress() != null) {
                            if (!information.getFactoryInspectionName().equals("") && !information.getFactoryInspectionAddress().equals("")) {
                                FileHashMap.put(information.getFactoryInspectionName(), information.getFactoryInspectionAddress());
                            }
                        }
                    }

                } else if (s.equals("2")) {
                    for (Information information : informationList) {
                        if (information.getCustomsName() != null && information.getCustomsAddress() != null) {
                            if (!information.getCustomsName().equals("") && !information.getCustomsAddress().equals("")) {
                                FileHashMap.put(information.getCustomsName(), information.getCustomsAddress());
                                return new AjaxResult(0, "生成文件成功", information.getCustomsAddress());
                            }
                        }
                    }

                } else if (s.equals("3")) {
                    for (Information information : informationList) {
                        if (information.getCommodityName() != null && information.getCommodityAddress() != null) {
                            if (!information.getCommodityName().equals("") && !information.getCommodityAddress().equals("")) {
                                FileHashMap.put(information.getCommodityName(), information.getCommodityAddress());
                            }
                        }
                    }
                } else if (s.equals("4")) {
                    for (Information information : informationList) {
                        if (information.getDisinfectName() != null && information.getDisinfectAddress() != null) {
                            if (!information.getDisinfectName().equals("") && !information.getDisinfectAddress().equals("")) {
                                FileHashMap.put(information.getDisinfectName(), information.getDisinfectAddress());
                            }
                        }
                    }
                } else {
                    for (Information information : informationList) {
                        if (information.getNucleicAcidName() != null && information.getNucleicAcidAddress() != null) {
                            if (!information.getNucleicAcidName().equals("") && !information.getNucleicAcidAddress().equals("")) {
                                FileHashMap.put(information.getNucleicAcidName(), information.getNucleicAcidAddress());
                            }
                        }
                    }
                }
            }
        }
        if (FileHashMap.size() != 0) {
            //定义新的字符串数组，存储需要合并的文件
           /* String[] files = new String[FileHashMap.size()];
            int i = 0;
            for (String value : FileHashMap.values()) {
                String replaceValue = value.replace("/profile", "D:/ruoyi/uploadPath");
                files[i] = replaceValue;
                i++;
            }
            PdfUtil pdfUtil = new PdfUtil();
            String path = "D:\\ruoyi\\uploadPath\\files\\" + new Date().getTime() + ".pdf";
//            String path = "D:/nyterp/uploadPath/files/" + new Date().getTime() + ".pdf";
            boolean b = pdfUtil.mergePdfFiles(files, path);
            System.out.println(path);
            if (b) {
                return new AjaxResult(0, "生成文件成功", path);
            } else {
                return AjaxResult.error("生成文件失败，请联系管理员");
            }*/
        } else {
            return AjaxResult.error("生成文件为空，请添加资料数据");
        }
        return AjaxResult.success("0", "生成文件成功");
    }

    /**
     * 打印随货单资料
     */
//    @GetMapping("/exportIsLeader/{src}")
//    public String exportIsLeader(@PathVariable("src") String src, ModelMap mmap) {
    @GetMapping("/exportIsLeader")
    public String exportIsLeader(String src, ModelMap mmap) {
        mmap.addAttribute("src", src);
        return "salegoods/exportIsLeader";
    }

    /**
     * 根据 表格中的id
     */
    @Transactional
    @Log(title = "保存打印出库单", businessType = BusinessType.INSERT)
    @PostMapping("/insertOutbounda")
    @ResponseBody
    public JSONObject insertOutbound(String[] data, Long saleGoodsId) {
        JSONObject jsonObject = new JSONObject();
        BigDecimal total = new BigDecimal("0.00");
        BigDecimal taxTotal = new BigDecimal("0.00");
//        for (int i = 0; i < data.length / 10; i++) {
        for (int i = 0; i < data.length / 11; i++) {
            if (data[i] != null) {
//                total = total.add(new BigDecimal(data[i * 10 + 7]));
//                taxTotal = taxTotal.add(new BigDecimal(data[i * 10 + 8]));
                total = total.add(new BigDecimal(data[i * 11 + 7]));
                taxTotal = taxTotal.add(new BigDecimal(data[i * 11 + 8]));
            } else {
                total = total.add(new BigDecimal("0.00"));
                taxTotal = taxTotal.add(new BigDecimal("0.00"));
            }
        }

        //data 每10个一组
        OutboundOrder outboundOrder = new OutboundOrder();
        //销货单id
        outboundOrder.setSaleGoodsId(saleGoodsId);
        //税率
        outboundOrder.setTaxRate(data[4]);
        //   outboundOrder.setAmount(total);
        outboundOrder.setTaxamount(taxTotal);
        //创建人
        outboundOrder.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        int a = iOutboundService.insertOutboundOrder(outboundOrder);

        if (data != null && data.length != 0) {
            //次数
            for (int i = 0; i < data.length / 11; i++) {
                OutboundModel outboundModel = new OutboundModel();
                outboundModel.setOutboundId(outboundOrder.getOutboundId());
                outboundModel.setProductId(Long.valueOf(data[i * 11]));
                outboundModel.setProductType(data[i * 11 + 1]);
                outboundModel.setBatch(data[i * 11 + 2]);
                outboundModel.setSaleorderModelId(Long.valueOf(data[i * 11 + 10]));
                int b = iOutboundService.insertOutboundModel(outboundModel);
            }
//            for (int i = 0; i < data.length / 10; i++) {
//                OutboundModel outboundModel = new OutboundModel();
//                outboundModel.setOutboundId(outboundOrder.getOutboundId());
//                outboundModel.setProductId(Long.valueOf(data[i * 10]));
//                outboundModel.setProductType(data[i * 10 + 1]);
//                outboundModel.setBatch(data[i * 10 + 2]);
//                outboundModel.setNum(Long.parseLong(data[i * 10 + 3]));
//                outboundModel.setPrice(new BigDecimal(data[i * 10 + 5]));
//                outboundModel.setTaxPrice(new BigDecimal(data[i * 10 + 6]));
//                outboundModel.setTotal(new BigDecimal(data[i * 10 + 7]));
//                outboundModel.setTaxTotal(new BigDecimal(data[i * 10 + 8]));
//                outboundModel.setSaleorderModelId(Long.valueOf(data[i * 10 + 10]));
//                int b = iOutboundService.insertOutboundModel(outboundModel);
//            }
        }

        if (a > 0) {
            jsonObject.put("success", "1");
            jsonObject.put("outboundId", outboundOrder.getOutboundId());
        }

        return jsonObject;

    }

    @Transactional
    @Log(title = "保存打印出库单", businessType = BusinessType.INSERT)
    @PostMapping("/insertOutbound")
    @ResponseBody
    public JSONObject insertOutbounda(@RequestBody Product product) {
        List<ProductModel> productModels = product.getProductModel();
        OutboundOrder outboundOrder = new OutboundOrder();
        outboundOrder.setTaxRate(productModels.get(0).getTaxRate());
        outboundOrder.setSaleGoodsId(product.getSaleGoodsId());
        JSONObject jsonObject = new JSONObject();
        OutboundModel outboundModel = new OutboundModel();
        Long amount = 0L;
        for (ProductModel item : productModels) {
            amount += item.getAmount();
        }

        outboundOrder.setAmount(amount);
        iOutboundService.insertOutboundOrder(outboundOrder);
        for (ProductModel item : productModels) {
            outboundModel.setOutboundId(outboundOrder.getOutboundId());
            outboundModel.setProductId(item.getProductId());
            outboundModel.setProductType(item.getProductType());
            outboundModel.setBatch(item.getBatch());
            outboundModel.setTaxPrice(item.getTaxPrice());
            outboundModel.setTaxTotal(item.getTaxTatol());
            outboundModel.setNum(item.getNum());
            outboundModel.setSaleorderModelId(item.getSaleorderModelId());
            iOutboundService.insertOutboundModel(outboundModel);
        }
        jsonObject.put("outboundId", outboundOrder.getOutboundId());
        return jsonObject;
    }

    /**
     * 根据生成的出库记录表id 打印预览
     */
    @Transactional
    @GetMapping("/dataIntoOutorderThree")
    @ResponseBody
    public JSONObject dataIntoOutorderThree(@RequestParam(value = "outboundId") Long outboundId, @RequestParam(value = "rowFalg") int rowFalg, @RequestParam(value = "saleGoodsId") Long saleGoodsId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleGoodsId", saleGoodsId);
        hashMap.put("outboundId", outboundId);
        hashMap.put("deptId", sysUser.getCompanyId());
        SaleGoodsOrder saleGoodsOrder = iOutboundService.selectSaleGoodsByOutboundId(hashMap);
        List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder.getSaleGoodsModels();
        for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
            if (saleGoodsModel.getAllNum() == 0) {
                if (saleGoodsModel.getUnits().equals("0")) {
                    saleGoodsModel.setUnit("盒");
                } else if (saleGoodsModel.getUnits().equals("1")) {
                    saleGoodsModel.setUnit("支");
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        //本公司名称
        jsonObject.put("deptNameVal", iSysDeptService.selectDeptById(sysUser.getCompanyId()).getDeptName());

        //单据编号 是销货单的编号
        jsonObject.put("contractNo", saleGoodsOrder.getSaleGoodsNum());
        //客户名称
        jsonObject.put("purchaseName", saleGoodsOrder.getDeptName());
        //单据日期 contractDate
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        jsonObject.put("contractDate", fmt.format(saleGoodsOrder.getSaleGoodsDate()));
        Long customerId = saleGoodsOrder.getCustomerId();

        //客户地址
        Company company = iCompanyServer.selectByCompanyId(customerId);
        jsonObject.put("contractAddress", company.getRasProvince() + company.getRasCity() + company.getRasDistrict() + company.getRasAddress());

        //收货地址 warehouseAddress 当前登陆人
//        HashMap hashMap1 = new HashMap();
//        hashMap1.put("deptId", ShiroUtils.getSysUser().getCompanyId());
//        hashMap1.put("companyId", saleGoodsOrder.getCustomerId());
//        hashMap1.put("gradeStatus", "02");
//        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(hashMap1);
//        Company mycompany = iCompanyServer.selectByCompanyId(ShiroUtils.getSysUser().getCompanyId());
//        jsonObject.put("warehouseAddress", mycompany.getProvince() + mycompany.getCity() + mycompany.getOtherCorporateAddress());
        jsonObject.put("warehouseAddress", company.getWarehouseAddress());

        //公司电话
//        jsonObject.put("custPhone", iCompanyInvoiceService.selectByCompanyId(customerId).getCorporateRegisterPhone());
        jsonObject.put("custPhone", company.getCorporateRegisterPhone());

        //销售订单产
        JSONArray jsonArrayModel = new JSONArray();
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            jsonArrayModel.add(saleGoodsOrder.getSaleGoodsModels().get(i));
        }
        jsonObject.put("models", jsonArrayModel);

        //总数量
        int totalNum = 0;
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            totalNum += saleGoodsOrder.getSaleGoodsModels().get(i).getNum();
        }
        jsonObject.put("totalNum", totalNum);

        //总金额
        BigDecimal totalMoney = new BigDecimal("0.00");
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            totalMoney = totalMoney.add(saleGoodsOrder.getSaleGoodsModels().get(i).getTaxTotal());
        }

        jsonObject.put("totalMoney", totalMoney);

        //制单人
        jsonObject.put("makeOrderName", iSysUserService.selectUserByLoginName(saleGoodsOrder.getCreateBy()).getUserName());

        //收货人及联系电话
//        String str = companyOther.getConsigneeAndPhone();
//        String str = company.getWarehousePhone();
//
//        String reg = "[^\u4e00-\u9fa5]";
//        if (!"".equals(str) && str != null) {
//            str = str.replaceAll(reg, "");
//        } else {
//            str = "";
//        }
//        jsonObject.put("consignee", str);
        jsonObject.put("consignee", company.getWarehouseBy());
        //出库单说明信息
        JSONArray jsonContractTerms = new JSONArray();
        Company company1 = iCompanyServer.selectByCompanyId(sysUser.getCompanyId());
        String contractTerms = company1.getOutboundDeliveryMemo();
        if (contractTerms == null || "".equals(contractTerms)) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "您的出库单说明信息为空,请先在个人信息-我的公司档案完善出库单说明信息。");
            throw new RuntimeException("您的出库单说明信息为空,请先在个人信息-我的公司档案完善出库单说明信息。");
        }
        if (contractTerms != null) {
            //根据回车进行分割
            String[] contractTermsArr = contractTerms.split("\\r?\\n");
            for (int i = 0; i < contractTermsArr.length; i++) {
                //每行108个字符
                String[] strings = Util.stringToArray(contractTermsArr[i]);
                String interception = Util.interception(strings, 108);
                //根据回车进行分割
                String[] split = interception.split("换行aaaaa");
                for (int j = 0; j < split.length; j++) {
                    String s = split[j];
                    //第一行的时候拼接上 “说明：”
                    jsonContractTerms.add(s);
                }
            }
            jsonObject.put("contractTerms", jsonContractTerms);
        } else {
            jsonObject.put("contractTerms", "");
        }
        return jsonObject;
    }


    @Log(title = "审核销售订单", businessType = BusinessType.UPDATE)
    @GetMapping("/auditSale")
    @ResponseBody
    public AjaxResult auditSale(@RequestParam(value = "saleGoodsId", required = false) Long saleGoodsId,
                                @RequestParam(value = "saleGoodsStatus", required = false) String saleGoodsStatus) {
        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
        saleGoodsOrder.setSaleorderId(saleGoodsId);
        saleGoodsOrder.setSaleGoodsStatus(saleGoodsStatus);
        // 状态流转
        int result = iSaleGoodsService.auditSale(saleGoodsOrder);
        return toAjax(result);
    }

    /**
     * 销货单发货
     *
     * @param saleGoodsId 销货单ID
     * @return 结果
     */
    @GetMapping("/shipments")
    @ResponseBody
    public Map<String, Object> shipments(String saleGoodsId) {
        return iSaleGoodsService.shipments(saleGoodsId);
    }

    /**
     * 打印快递单
     * @param saleGoodsId
     * @return
     */
    @GetMapping("printExpressOrder")
    @ResponseBody
    public Map<String, Object> printExpressOrder(Long saleGoodsId) {
        Map<String, Object> result = iSaleGoodsService.printExpressOrder(saleGoodsId);
        return result;
    }

    /**
     * 根据生成的出库记录表id 打印预览
     */
    @Transactional
    @GetMapping("/dataIntoOutorderTwo")
    @ResponseBody
    public JSONObject dataIntoOutorderTwo(@RequestParam(value = "outboundId", required = false) Long outboundId, @RequestParam(value = "rowFalg", required = false) int rowFalg, @RequestParam(value = "saleGoodsId", required = false) Long saleGoodsId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleGoodsId", saleGoodsId);
        hashMap.put("outboundId", outboundId);
        hashMap.put("deptId", sysUser.getCompanyId());
//        SaleGoodsOrder saleGoodsOrder = iOutboundService.selectSaleGoodsByOutboundIdes(hashMap);
        SaleGoodsOrder saleGoodsOrder = iOutboundService.selectSaleGoodsByOutboundId(hashMap);
        JSONObject jsonObject = new JSONObject();
        //本公司名称
        jsonObject.put("deptNameVal", iSysDeptService.selectDeptById(sysUser.getCompanyId()).getDeptName());
        //单据编号 是销货单的编号
        jsonObject.put("contractNo", saleGoodsOrder.getSaleGoodsNum());
        //客户名称
        jsonObject.put("purchaseName", saleGoodsOrder.getDeptName());
        //单据日期 contractDate
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        jsonObject.put("contractDate", fmt.format(saleGoodsOrder.getSaleGoodsDate()));
        Long customerId = saleGoodsOrder.getCustomerId();
        //客户地址
        Company company = iCompanyServer.selectByCompanyId(customerId);
        jsonObject.put("contractAddress", company.getRasProvince() + company.getRasCity() + company.getRasDistrict() + company.getRasAddress());
        //收货地址 warehouseAddress 当前登陆人
//        HashMap hashMap1 = new HashMap();
//        hashMap1.put("deptId", ShiroUtils.getSysUser().getCompanyId());
//        hashMap1.put("companyId", saleGoodsOrder.getCustomerId());
//        hashMap1.put("gradeStatus", "02");
//        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(hashMap1);
//        Company mycompany = iCompanyServer.selectByCompanyId(ShiroUtils.getSysUser().getCompanyId());
//        jsonObject.put("warehouseAddress", mycompany.getProvince() + mycompany.getCity() + mycompany.getOtherCorporateAddress());
        jsonObject.put("warehouseAddress", company.getWarehouseAddress());

        //公司电话
        //jsonObject.put("custPhone", iCompanyInvoiceService.selectByCompanyId(customerId).getCorporateRegisterPhone());
        jsonObject.put("custPhone", company.getCorporateRegisterPhone());

        //销售订单产品
        JSONArray jsonArrayModel = new JSONArray();
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            jsonArrayModel.add(saleGoodsOrder.getSaleGoodsModels().get(i));
        }
        jsonObject.put("models", jsonArrayModel);
        //总数量
        int totalNum = 0;
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            totalNum += saleGoodsOrder.getSaleGoodsModels().get(i).getNum();
        }
        jsonObject.put("totalNum", totalNum);
        //总金额
        BigDecimal totalMoney = new BigDecimal("0.00");
        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size() - rowFalg; i++) {
            totalMoney = totalMoney.add(saleGoodsOrder.getSaleGoodsModels().get(i).getTaxTotal());
        }
        jsonObject.put("totalMoney", totalMoney);
        //制单人
        jsonObject.put("makeOrderName", iSysUserService.selectUserByLoginName(SecurityUtils.getLoginUser().getUser().getUserName()));

        //收货人

        //收货人及联系电话
//        String str = companyOther.getConsigneeAndPhone();
//        String str = company.getWarehousePhone();
//
//        String reg = "[^\u4e00-\u9fa5]";
//        if (!"".equals(str) && str != null) {
//            str = str.replaceAll(reg, "");
//        } else {
//            str = "";
//        }
//        jsonObject.put("consignee", str);
        jsonObject.put("consignee", company.getWarehouseBy());
        //出库单说明信息

        JSONArray jsonContractTerms = new JSONArray();

        Company company1 = iCompanyServer.selectByCompanyId(sysUser.getCompanyId());
        String contractTerms = company1.getOutboundDeliveryMemo();

        if (contractTerms == null || "".equals(contractTerms)) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "您的出库单说明信息为空,请先在个人信息-我的公司档案完善出库单说明信息。");
            throw new RuntimeException("您的出库单说明信息为空,请先在个人信息-我的公司档案完善出库单说明信息。");
        }


        if (contractTerms != null) {
            //根据回车进行分割
            String[] contractTermsArr = contractTerms.split("\\r?\\n");

            for (int i = 0; i < contractTermsArr.length; i++) {
                //每行108个字符
                String[] strings = Util.stringToArray(contractTermsArr[i]);
                String interception = Util.interception(strings, 108);
                //根据回车进行分割
                String[] split = interception.split("换行aaaaa");
                for (int j = 0; j < split.length; j++) {
                    String s = split[j];
                    //第一行的时候拼接上 “说明：”
                    jsonContractTerms.add(s);
                }

            }
            jsonObject.put("contractTerms", jsonContractTerms);
        } else {
            jsonObject.put("contractTerms", "");
        }
        return jsonObject;
    }

    @GetMapping("/printsheet")
    @ResponseBody
    public Map<String, Object> postExpressDelivery(@RequestParam(value = "msgData") String msgData) throws Exception {
        Map<String, Object> resMap = expressDeliveryService.PrintSheet(msgData);
        return resMap;
    }

    /**
     * 出库记录单 剩余的数据
     */
    @PostMapping("/dataIntoOutorderTwoOtherData")
    @ResponseBody
    public JSONObject dataIntoOutorderTwoOtherData(String[] tableData, Long saleGoodsId, Long outboundId) {
        //每一页封装为一个JSONObject
        JSONObject jsonObject = new JSONObject();
        //处理数据 传过来的以，分割的字符串
        //每条数据查询出从表主键id 放到集合中
        ArrayList<Long> tableDataId = new ArrayList();

        for (int i = 0; i < tableData.length; i++) {
            String[] split = tableData[i].split(",");
            HashMap<String, Object> hashMapa = new HashMap();
            //salegoodsid
            hashMapa.put("saleGoodsId", saleGoodsId);
            //outboundId
            hashMapa.put("outboundId", outboundId);
            //deptId
            hashMapa.put("deptId", ShiroUtils.getSysUser().getCompanyId());
            //productId
            hashMapa.put("productId", split[0]);
            //productType
            hashMapa.put("productType", split[1]);
            //batch
            hashMapa.put("batch", split[8]);
            SaleGoodsModel model = iOutboundService.selectSaleGoodsByOutboundIds(hashMapa);
            tableDataId.add(model.getSaleGoodsModelId());
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleGoodsId", saleGoodsId);
        hashMap.put("outboundId", outboundId);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        SaleGoodsOrder saleGoodsOrder = iOutboundService.selectSaleGoodsByOutboundId(hashMap);

        //新建对比数组，用于判断执行什么操作
        ArrayList<Long> arrayList = new ArrayList();
        for (SaleGoodsModel model : saleGoodsOrder.getSaleGoodsModels()) {
            arrayList.add(model.getSaleGoodsModelId());
        }
        //排序
        Collections.sort(arrayList);
        //记录最初的数据数量
        int arraySize = arrayList.size();

        //数组中剩余的数就是需要再打印的数据
        for (Long o1 : tableDataId) {
            Iterator<Long> iterator = arrayList.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().equals(o1)) {
                    iterator.remove();
                }
            }
        }
        //剩下的则是 要重新生成的 随货单
        //分为几页arrayList.size()/tableData.length+1

        jsonObject.put("page", (int) Math.ceil((double) arrayList.size() / tableData.length));

        //如果剩余的只有一页了
        if (arrayList.size() <= tableData.length) {
            //总数量
            int totalNuma = 0;
            //总金额
            BigDecimal totalMoneya = new BigDecimal("0.00");
            JSONArray jsonArrayModel = new JSONArray();
            for (int j = 0; j < arrayList.size(); j++) {
                HashMap hashMap1 = new HashMap();
                //salegoodsid
                hashMap1.put("saleGoodsId", saleGoodsId);
                //outboundId
                hashMap1.put("outboundId", outboundId);
                //saleGoodsModelId
                hashMap1.put("saleGoodsModelId", arrayList.get(j));
                //deptId
                hashMap1.put("deptId", ShiroUtils.getSysUser().getCompanyId());
                //销售订单产品
                SaleGoodsModel model = iOutboundService.selectSaleGoodsByOutboundIds(hashMap1);

                jsonArrayModel.add(model);
                totalNuma += model.getNum();
                totalMoneya = totalMoneya.add(model.getTaxTotal());
            }
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("models", jsonArrayModel);
            jsonObject1.put("totalNum", totalNuma);
            jsonObject1.put("totalMoney", totalMoneya);
            jsonObject.put("page0", jsonObject1);
        } else {
            //这里则是 剩余的超过一页
            //外层for循环控制 第几页
            //记录当时集合数量
            int size = arrayList.size();
            for (int i = 0; i < (int) Math.ceil((double) size / tableData.length); i++) {
                //当页总数量
                int totalNum = 0;
                //当页总金额
                BigDecimal totalMoney = new BigDecimal("0.00");
                //取最后一页的条数 取模
                int lastRow = arraySize % tableData.length;
                //不是最后一页的话
                //存放model数据
                JSONArray jsonArrayModel1 = new JSONArray();
                if (i != ((int) Math.ceil((double) size / tableData.length)) - 1) {
                    for (int j = i * tableData.length; j < tableData.length + i * tableData.length; j++) {
                        HashMap hashMap2 = new HashMap();
                        //salegoodsid
                        hashMap2.put("saleGoodsId", saleGoodsId);
                        //outboundId
                        hashMap2.put("outboundId", outboundId);
                        //saleGoodsModelId
                        hashMap2.put("saleGoodsModelId", arrayList.get(j));
                        //deptId
                        hashMap2.put("deptId", ShiroUtils.getSysUser().getCompanyId());
                        //销售订单产品
                        SaleGoodsModel model = iOutboundService.selectSaleGoodsByOutboundIds(hashMap2);
                        jsonArrayModel1.add(model);
                        totalNum += model.getNum();
                        totalMoney = totalMoney.add(model.getTaxTotal());
                    }
                } else {
                    //是最后一页的话
                    for (int j = arrayList.size() - lastRow; j < arrayList.size(); j++) {
                        HashMap hashMap3 = new HashMap();
                        //salegoodsid
                        hashMap3.put("saleGoodsId", saleGoodsId);
                        //outboundId
                        hashMap3.put("outboundId", outboundId);
                        //outboundModelId
                        hashMap3.put("saleGoodsModelId", arrayList.get(j));
                        //deptId
                        hashMap3.put("deptId", ShiroUtils.getSysUser().getCompanyId());
                        //销售订单产品
                        SaleGoodsModel model = iOutboundService.selectSaleGoodsByOutboundIds(hashMap3);

                        jsonArrayModel1.add(model);
                        totalNum += model.getNum();
                        totalMoney = totalMoney.add(model.getTaxTotal());
                    }
                }
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("models", jsonArrayModel1);
                jsonObject1.put("totalNum", totalNum);
                jsonObject1.put("totalMoney", totalMoney);
                jsonObject.put("page" + i, jsonObject1);

            }

        }
        jsonObject.put("lastRow", tableData.length);
        return jsonObject;
    }

    /**
     * 查看销货订单
     */
    @GetMapping("/look/{saleGoodsId}")
    public String look(@PathVariable("saleGoodsId") Long saleGoodsId, ModelMap mmap) {
        HashMap hashMap = new HashMap();
        hashMap.put("saleGoodsId", saleGoodsId);
//        SaleGoodsOrder saleGoodsOrder = iSaleGoodsService.selectSaleGoodsById(hashMap);
        //查看销货订单的数据
        SaleGoodsOrder saleGoodsOrder = iSaleGoodsService.selectSaleGoodsByIdIsLook(hashMap);
        List<SaleGoodsModel> saleGoodsModelList = saleGoodsOrder.getSaleGoodsModels();
        for (SaleGoodsModel saleGoodsModel : saleGoodsModelList) {
            if (saleGoodsModel.getAllNum() == 0) {
                saleGoodsModel.setUnit(saleGoodsModel.getUnits());

            }

        }
        mmap.put("saleGoodsOrder", saleGoodsOrder);
        mmap.put("saleGoodsModels", saleGoodsOrder.getSaleGoodsModels());
        mmap.put("taxRate", iCompanyInvoiceService.selectByCompanyId(ShiroUtils.getSysUser().getCompanyId()));
        return "salegoods/look";
    }

    /**
     * 查看出库单记录
     */
    @GetMapping("/outorder/{saleGoodsId}")
    public String outorer(@PathVariable("saleGoodsId") Long saleGoodsId, Model model) {
        //OutboundOrder outboundOrder = iOutboundService.selectOutboundBySaleGoodsId(saleGoodsId);
        model.addAttribute("saleGoodsId", saleGoodsId);
        return "salegoods/outorder";
    }

    /**
     * 选择产品批次 带出数据
     */
    @PostMapping("/jsonToStr")
    @ResponseBody
    public JSONArray jsonToStr(String data) {
        JSONArray jsonArray = JSONArray.parseArray(data);
        return jsonArray;
    }

    /**
     * 选择销货单 带出数据
     */
    @GetMapping("/salesInvoice")
    @ResponseBody
    public Map<String, Object> salesInvoice(@RequestParam(value = "deptName", required = false) String deptName,
                                            @RequestParam(value = "beginTime", required = false) String beginTime,
                                            @RequestParam(value = "endTime", required = false) String endTime) {

        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
        saleGoodsOrder.setDeptName(deptName);
        saleGoodsOrder.setBeginTime(beginTime);
        saleGoodsOrder.setEndTime(endTime);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Map<String, Object> map = new HashMap<>();
        Long companyId = sysUser.getCompanyId();
        saleGoodsOrder.setDeptId(companyId);
        saleGoodsOrder.setSaleGoodsStatus("1");
        List<SaleGoodsOrder> saleGoodsOrderList = new ArrayList<SaleGoodsOrder>();
        List<SaleGoodsModel> saleGoodsModelList = new ArrayList<SaleGoodsModel>();
        if (deptName == null) {
            map.put("saleGoodsOrderList", saleGoodsOrderList);
            map.put("saleGoodsModelList", saleGoodsModelList);
            return map;
        }

        saleGoodsOrderList = iSaleGoodsService.selectSaleGoodsListInvoice(saleGoodsOrder);

        List<Long> saleGoodIdList = new ArrayList<>();
        SaleGoodsModel goodsModel = new SaleGoodsModel();
        goodsModel.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());

        List<SaleGoodsModel> goodsModels = new ArrayList<>();
        if (saleGoodsOrderList.size() != 0) {
            for (int i = saleGoodsOrderList.size() - 1; i >= 0; i--) {
                List<SaleGoodsModel> saleGoodsModels = saleGoodsOrderList.get(i).getSaleGoodsModels();
                if (saleGoodsModels.size() == 0 || saleGoodsModels == null) {
                    saleGoodsOrderList.remove(i);
                    continue;
                }

                Long saleGoodsId = saleGoodsOrderList.get(i).getSaleGoodsId();
                saleGoodIdList.add(saleGoodsId);
                goodsModel.setSaleGoodsId(saleGoodsId);
                goodsModels.add(goodsModel);
            }

            saleGoodsModelList = saleGoodsMapper.selectSaleGoodsModelByList(saleGoodIdList, sysUser.getCompanyId());
            for (SaleGoodsModel saleGoodsModel : saleGoodsModelList) {
                if (saleGoodsModel.getAllNum() != 0) {
                    if (saleGoodsModel.getUnit().equals("盒")) {
                        Long b = saleGoodsModel.getAllNum() / saleGoodsModel.getFactor();
                        saleGoodsModel.setRemainingNum(Integer.valueOf(Math.toIntExact(b)));
                    }
                }

            }
        }

        map.put("saleGoodsOrderList", saleGoodsOrderList);
        map.put("saleGoodsModelList", saleGoodsModelList);
        return map;
    }

    /**
     * 根据 选择 销售订单 子表的id 带出到 添加主界面 产品列表中
     *
     * @param rows 选择销售订单子表的id
     * @return 返回子表数据集合
     */
    @PostMapping("/selectModelDataByModelId/{rows}")
    @ResponseBody
    public List<SaleorderModel> selectModelDataByModelId(@PathVariable("rows") String rows) {
        List<SaleorderModel> list = iSaleorderService.selectModelDataByModelId(rows);
        for (SaleorderModel saleorderModel : list) {
            if (saleorderModel.getAllNum() != 0) {
                if (saleorderModel.getUnit().equals("盒")) {
                    Long a = saleorderModel.getFactor();
                    if (a != 0) {
                        Long c = saleorderModel.getWarehousingNum() / a;
                        saleorderModel.setWarehousingNum(c);
                    }
                }
            }

        }
        return list;
    }

    /**
     * 进入 选择批号界面
     */
    @GetMapping("/selectBatch/{saleorderModelId}")
    public Map<String, Object> selectBatchGet(@PathVariable("saleorderModelId") String saleorderModelId) {
        Map<String, Object> resMap = new HashMap<>();
        List<SaleorderModel> list = iSaleorderService.selectModelDataByModelId(saleorderModelId);
        SaleorderModel saleorderModel = list.get(0);
        if (saleorderModel.getUnit().equals("盒")) {
            int b = saleorderModel.getRemainingNum() / saleorderModel.getFactor().intValue();
            saleorderModel.setRemainingNum(b);
        }
        resMap.put("modelData", saleorderModel);
        return resMap;
    }

    /**
     * 修改销货单页面 进入 选择批号界面
     */
    @GetMapping("/selectBatchs/{saleorderModelId}/{saleGoodsId}/{index}")
    public String selectBatchGets(@PathVariable("saleorderModelId") String saleorderModelId, @PathVariable("saleGoodsId") String saleGoodsId, @PathVariable("index") String index, Model model) {
        HashMap hashMap = new HashMap();
        hashMap.put("saleorderModelId", saleorderModelId);
//        hashMap.put("saleGoodsId", saleGoodsId);
        hashMap.put("saleGoodsId", saleGoodsId);
        SaleorderModel saleorderModel = iSaleorderService.selectBatchModel(hashMap);
        if (saleorderModel.getUnit().equals("盒")) {
            List<Integer> list1 = procurementServer.selectProductType(saleorderModel.getProductType());
            int a = list1.get(0);
            if (a != 0) {
                int b = saleorderModel.getRemainingNum() / a;
                saleorderModel.setRemainingNum(b);

            }

        }
        model.addAttribute("modelData", saleorderModel);
        model.addAttribute("index", index);
        return "salegoods/editSelectBatch";
    }

    /**
     * 选择批号界面 库存列表
     */
    @GetMapping("/selectWarehousing")
    @ResponseBody
    public Map<String, Object> selectWarehousing(@RequestParam(value = "productId", required = false) Long productId,
                                                 @RequestParam(value = "productType", required = false) String productType,
                                                 @RequestParam(value = "unit", required = false) String unit,
                                                 @RequestParam(value = "saleorderModelId", required = false) String saleorderModelId) {

        Map<String, Object> resMap = new HashMap<>();
        List<SaleorderModel> list = iSaleorderService.selectModelDataByModelId(saleorderModelId);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        hashMap.put("productId", productId);
        hashMap.put("productType", productType);
        List<Warehousing> warehousing = iSaleorderService.selectWarehousing(hashMap);
        if (warehousing.size() != 0) {
            if (unit.equals("盒") || unit == "盒") {
                for (Warehousing item : warehousing) {
                    long b = item.getAmount() / item.getFactor();
                    item.setAmount(b);
                }
                for (SaleorderModel item : list) {
                    Long b = item.getRemainingNum() / item.getFactor();
                    item.setRemainingNum(b.intValue());
                }
            }
        }

        resMap.put("saleorderModel", list);
        resMap.put("warehousing", warehousing);
        return resMap;
    }

    /**
     * 查询供应商的绑定业务员
     */
    @GetMapping("/selectUser/{companyId}")
    @ResponseBody
    public AjaxResult selectUser(@PathVariable("companyId") Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        map.put("companyId", companyId);
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther != null) {
            return AjaxResult.success(companyOther);
        } else {
            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
        }
    }

    public String getStr() {
        int len = 16;
        Random r = new Random();
        StringBuilder rs = new StringBuilder();
        for (int i = 0; i < len; i++) {
            rs.append(r.nextInt(10));
        }
        String a = rs.toString();
        return a;
    }

    public String getStrNew() {
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String secondsTimestamp = String.valueOf(System.currentTimeMillis() / 1000);
        return format + secondsTimestamp;
    }


    @Log(title = "销货订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SaleGoodsExcel saleGoodsExcel) {

        List<SaleGoodsExcel> list = iSaleGoodsService.queryExcel(saleGoodsExcel);
        // 默认为完整版
        if (ObjectUtil.isEmpty(saleGoodsExcel.getConstruction())) {
            saleGoodsExcel.setConstruction("0");
        }

        if ("0".equals(saleGoodsExcel.getConstruction())) {// 完整版
            ExcelUtil<SaleGoodsExcel> util = new ExcelUtil<>(SaleGoodsExcel.class);
            util.exportExcel(response, list, "销货订单记录");

        } else if("1".equals(saleGoodsExcel.getConstruction())) { // 降版1 不包含出库批号
            List<SaleGoodsExcelDto> dto = BeanUtil.copyToList(list, SaleGoodsExcelDto.class);
            ExcelUtil<SaleGoodsExcelDto> util = new ExcelUtil<>(SaleGoodsExcelDto.class);
            util.exportExcel(response, dto, "销货单记录");
        }

    }
}
